package dao

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"rank-srv/global"
	"rank-srv/internal/model"
	__ "rank-srv/proto"
	"strconv"
)

type TopShopImpl interface {
	Top()
}
type TopShop struct {
}

func NewTopShop() *TopShop {
	return &TopShop{}
}
func (t *TopShop) Top() []*__.TopList {

	var shop model.Shop

	ShopList := shop.ShopList(global.DB)

	key := fmt.Sprintf("top:shop")

	TopRedis := make([]*redis.Z, 0, len(ShopList))

	shopMap := make(map[int64]model.Shop, len(ShopList)) // 假设ID是int64类型
	for _, m := range ShopList {
		shopMap[int64(m.ID)] = m
	}

	for _, m := range ShopList {
		TopRedis = append(TopRedis, &redis.Z{
			Score:  m.Price,
			Member: m.ID,
		})
	}
	global.Rdb.ZAdd(context.Background(), key, TopRedis...)

	result, err := global.Rdb.ZRevRangeWithScores(context.Background(), key, 0, -1).Result()
	if err != nil {
		return nil
	}
	fmt.Println(result)
	var rankList []*__.TopList
	for _, z := range result {
		// 先将Member转为字符串（因为存储时是字符串）
		memberStr, ok := z.Member.(string)
		if !ok {
			continue // 跳过非字符串的Member
		}
		// 将字符串ID转为int64，与shopMap的key匹配
		shopID, err := strconv.ParseInt(memberStr, 10, 64)
		if err != nil {
			continue // 跳过无效ID
		}
		fmt.Println(shopID)
		// 从映射中获取商品信息
		shopInfo, exists := shopMap[shopID]
		if !exists {
			continue
		}
		// 封装结果
		rankList = append(rankList, &__.TopList{
			Name:   shopInfo.Name,
			Price:  float32(shopInfo.Price),
			Number: int64(shopInfo.Number),
		})
	}
	fmt.Println("rankList", rankList)
	return rankList

}
